import os
import sqlite3
import shutil
import win32com.client
import win32process
import win32api
import win32con
import psutil
from http.cookiejar import MozillaCookieJar

from PyQt5.QtCore import QThread


def is_chrome_running():
    for proc in psutil.process_iter(['name']):
        if proc.info['name'] and 'chrome' in proc.info['name'].lower():
            return True
    return False


def extract_youtube_cookies_to_txt(output_path='cookies.txt'):
    chrome_user_data = os.path.expandvars(r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\Network\Cookies')
    if not os.path.exists(chrome_user_data):
        print("找不到 Chrome cookies 数据库")
        return False

    tmp_copy_path = os.path.join(os.getcwd(), 'chrome_cookies_tmp')
    os.makedirs(tmp_copy_path, exist_ok=True)
    db_copy = os.path.join(tmp_copy_path, 'Cookies')

    try:
        shutil.copy2(chrome_user_data, db_copy)
    except PermissionError:
        print("无法访问 Chrome Cookies 文件，可能正在运行中")
        return False

    conn = sqlite3.connect(db_copy)
    cursor = conn.cursor()

    # 只提取 YouTube 域的 cookies
    cursor.execute("SELECT host_key, name, value, path, expires_utc, is_secure FROM cookies WHERE host_key LIKE '%youtube.com%'")

    cj = MozillaCookieJar(output_path)
    for host, name, value, path, expires, is_secure in cursor.fetchall():
        cookie = f"{host}\tTRUE\t{path}\t{'TRUE' if is_secure else 'FALSE'}\t{int(expires/1e6 - 11644473600)}\t{name}\t{value}\n"
        with open(output_path, 'a', encoding='utf-8') as f:
            f.write(cookie)

    conn.close()
    os.remove(db_copy)
    return True


def prepare_youtube_cookies():
    if is_chrome_running():
        print("Chrome 正在运行，跳过拷贝 Cookies。")
        return False
    else:
        print("Chrome 未运行，提取 cookies...")
        return extract_youtube_cookies_to_txt()

import os
import sqlite3
import shutil
import tempfile
from http.cookiejar import MozillaCookieJar

def extract_youtube_cookies_to_txt(output_path='cookies.txt'):
    # Chrome cookies 原始路径
    chrome_user_data = os.path.expandvars(r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\Network\Cookies')

    if not os.path.exists(chrome_user_data):
        print("找不到 Chrome Cookies 数据库")
        return False

    # 创建临时目录和副本
    tmp_dir = tempfile.mkdtemp()
    db_copy = os.path.join(tmp_dir, 'Cookies')

    try:
        shutil.copy2(chrome_user_data, db_copy)
    except Exception as e:
        print(f"拷贝 Cookies 数据库失败：{e}")
        return False

    try:
        conn = sqlite3.connect(db_copy)
        cursor = conn.cursor()
        cursor.execute("""
            SELECT host_key, name, value, path, expires_utc, is_secure
            FROM cookies
            WHERE host_key LIKE '%youtube.com%'
        """)

        cj = MozillaCookieJar(output_path)
        with open(output_path, 'w', encoding='utf-8') as f:
            for host, name, value, path, expires, is_secure in cursor.fetchall():
                # Convert Chrome's timestamp to Unix timestamp
                expires_ts = int(expires / 1e6 - 11644473600)
                cookie_line = f"{host}\tTRUE\t{path}\t{'TRUE' if is_secure else 'FALSE'}\t{expires_ts}\t{name}\t{value}\n"
                f.write(cookie_line)

        conn.close()
        print("成功提取 cookies 到 cookies.txt")
        return True

    except Exception as e:
        print(f"读取 cookies 失败：{e}")
        return False

    finally:
        try:
            os.remove(db_copy)
            os.rmdir(tmp_dir)
        except Exception:
            pass

import os
import ctypes
import tempfile

def copy_locked_file(src_path, dst_path):
    GENERIC_READ = 0x80000000
    FILE_SHARE_READ = 0x00000001
    FILE_SHARE_WRITE = 0x00000002
    OPEN_EXISTING = 3
    FILE_ATTRIBUTE_NORMAL = 0x80

    kernel32 = ctypes.windll.kernel32

    handle = kernel32.CreateFileW(
        src_path,
        GENERIC_READ,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        None,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        None
    )

    if handle == -1:
        raise PermissionError(f"无法访问被锁定的文件：{src_path}")

    # 创建目标文件
    with open(dst_path, 'wb') as out_file:
        buffer = ctypes.create_string_buffer(4096)
        bytes_read = ctypes.c_ulong(0)
        while kernel32.ReadFile(handle, buffer, 4096, ctypes.byref(bytes_read), None) and bytes_read.value:
            out_file.write(buffer.raw[:bytes_read.value])

    kernel32.CloseHandle(handle)

